package com.sjf.JavaNIO.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * SocketChannel用来TCP/IP的传输
 *
 * @author <huangtang>
 * @since 2022/4/13 17:42
 **/
public class SocketChannelDemo {

    public static void main ( String[] args ) throws Exception {
        //创建SocketChannel
        SocketChannel socketChannel = SocketChannel.open (new InetSocketAddress ("www.baidu.com" , 80));

        //设置阻塞和非阻塞
        //设置阻塞时会在read进行等待，直接有数据进来或者等待超时再继续执行，否则会一直等待
        socketChannel.configureBlocking (true);//设置非阻塞

        //读操作
        ByteBuffer buffer = ByteBuffer.allocate (16);
        socketChannel.read (buffer);
        socketChannel.close ();
        System.out.println ("read over");
    }
}
